//
//  CPJListViewModel.swift
//  Sina
//
//  Created by YYY on 2017/8/14.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import Foundation

/*
 如果没有任何父类，希望在开发中进行调试，输出调试信息，需要
 1:遵守 CustomStringConvertible
 2:实现description计算型属性
 
 
 关于表格的性能优化
 1:尽量的少计算，所有需要的素材提前计算好
 2:控件上不要设置圆角半径，所有图像的渲染属性，都要注意
 3:不要动态的创建控件，所有需要的控件，都需要提前创建好，在显示的时候，根据数据隐藏或显示
 4:cell中的控件层次越少越好，数量越少越好
 5:要测量，不要猜测
 6:如果每次在setter方法中做计算，会影响执行性能。
 7：行高一定要缓存（如果不需要缓存行高，刷新帧率就很高，可以不缓存。）
 缓存行高是解决性能的最佳途径
 
 高级优化：离屏渲染、栅格化（如果检测到cell的性能已经很好，就不需要渲染）
 离屏渲染需要在CPU和GPU之间快速切换，并且耗电比较厉害
 */

class CPJListViewModel: CustomStringConvertible
{
    var homePageModel: CPJHomePageModel
    
    //会员图标
    var memberIcon: UIImage?
    //认证图标
    var vertifyIcon: UIImage?
    
    //转发
    var retweetString: String?
    
    //评论
    var commentString: String?
    
    //赞
    var likeString: String?
    
    //配图视图大小
    var pictureSize = CGSize()
    
    //行高
    var rowHeight: CGFloat = 0
    
    //来源
    //var sourceString: String?
    
    //微博正文的属性文本
    var statusAttributeString: NSAttributedString?
    
    //转发微博正文的属性文本
    var retweetAttributeString: NSAttributedString?
    
    //配图的返回
    var picture_urls: [CPJPictureModel]?
    {
        return homePageModel.retweeted_status?.pic_urls ?? homePageModel.pic_urls
    }
    
    //数据加载展示的时候，仅执行第一次
    init(model: CPJHomePageModel)
    {
        homePageModel = model
        
        //会员图标
        let rank = homePageModel.user?.mbrank ?? 1       
        if rank>=1 && rank<7
        {
            let imageName = "common_icon_membership_level\(rank)"
            memberIcon = UIImage(named: imageName)
        }
        
        //认证类型
        //-1:没有认证
        //0:认证用户
        //2,3,5:企业认证
        //220:达人
        //认证图标
        let vertifyNumber = model.user?.verified_type ?? -1
        switch vertifyNumber
        {
        case 0:
            //认证用户
            vertifyIcon = UIImage(named: "avatar_vip")
            break
        case 2,3,5:
        //企业认证
            vertifyIcon = UIImage(named: "avatar_enterprise_vip")
            break
        case 220:
        //达人
            vertifyIcon = UIImage(named: "avatar_grassroot")
            break
        default:
            break
        }
        
        //转发、评论、赞
        retweetString = toolBarText(count: model.reposts_count, defaultStr: "转发")
        
        commentString = toolBarText(count: model.comments_count, defaultStr: "评论")
        
        likeString = toolBarText(count: model.attitudes_count, defaultStr: "赞")
        
        //配图图片大小
        pictureSize = calculatePictureSize(count: picture_urls?.count)
        
        
        //转发内容
        //sourceString = "来自" + (model.source?.regularExpression()?.text ?? "")
        
        let originalFont = UIFont.systemFont(ofSize: 15)
        let retweetFont = UIFont.systemFont(ofSize: 14)
        let retText = "@" + (model.retweeted_status?.user?.screen_name ?? "") + ":" + (model.retweeted_status?.text ?? "")
      
        //微博正文的属性文本
        statusAttributeString = EmotionManager.shared.emoticonString(string: model.text ?? "", font: originalFont)

        //转发微博正文的属性文本
        retweetAttributeString = EmotionManager.shared.emoticonString(string: retText, font: retweetFont)

        //retweetAttributeString =
        //根据视图模型内容计算行高
        updateRowHeight()
    }
    
    
    /// 计算图片视图的大小
    ///
    /// - Parameter count: 图片数量
    /// - Returns: 返回图片大小
    private func calculatePictureSize(count: Int?) -> CGSize
    {
        if count == 0 || count == nil
        {
            return CGSize()
        }
        // 123
        // 456
        // 789
        let row = CGFloat((count! - 1)/3 + 1)
        let height = CPJPictureViewOutterMargin + row * CPJPictureItemWidth + (row - 1) * CPJPictureViewInnerMargin
        return CGSize(width: CPJPictureViewWidth, height: height)
    }
    //设置底部分栏文字
    private func toolBarText(count: Int,defaultStr: String) -> String
    {
        if count == 0
        {
            return defaultStr
        }
        if count < 10000
        {
            return count.description
        }
        
        return String(format: "%.2f 万",Double(count/10000))
    }
    
    var description: String
    {
        return homePageModel.description
    }
    
    //更新配图视图单张图片的大小
    func updateSingleImageSize(image: UIImage)
    {
        var size = image.size
        
        //最大宽度
        let maxWidth: CGFloat = 200
        //最小宽度
        let minWidth: CGFloat = 40
     
        //图片过宽处理
        if size.width > maxWidth
        {
            size.width = 200
            size.height = size.width * image.size.height/image.size.width
        }
        
        //图片过窄处理
        if size.width < minWidth
        {
            size.width = minWidth
            size.height = size.width * image.size.height/image.size.width/4
        }
        
        //图片过高处理,图片填充模式是scaleToFill,图片高度减小会自动裁剪
        if size.height > 200
        {
            size.height = 200
        }
        size.height += CPJPictureViewOutterMargin
        pictureSize = size
        //根据视图模型内容计算行高
        updateRowHeight()
    }
    
    //根据视图模型内容计算行高
    func updateRowHeight()
    {
        //顶部部视图高度
        let topViewHeight: CGFloat = 12
        //间距
        let margin: CGFloat = 12
        //头像高度
        let iconHeight: CGFloat = 34

        //底部工具栏高度
        let toolbarHeight: CGFloat = 35
        
        //原创正文高度
        var originalHeight: CGFloat = 0
        let originalSize = CGSize(width: kScreenWidth - 2 * margin, height: CGFloat(MAXFLOAT))
        let originalFont = [NSFontAttributeName: UIFont.systemFont(ofSize: 15)]
        
        //转发微博的正文高度
        var retweetHeight: CGFloat = 0
        let retweetFont = [NSFontAttributeName: UIFont.systemFont(ofSize: 14)]
        
        //定义高度
        var height: CGFloat = 0
        
        height += topViewHeight + 2 * margin + iconHeight
        
        //原创正文内容
        if let originalText = statusAttributeString
        {
            originalHeight = originalText.boundingRect(with: originalSize, options: [.usesLineFragmentOrigin], context: nil).height
            height += originalHeight
        }
        
        if homePageModel.retweeted_status != nil
        {
            height += 2 * margin
            //有转发微博
            if let text = retweetAttributeString
            {
                retweetHeight = text.boundingRect(with: originalSize, options: [.usesLineFragmentOrigin], context: nil).height
                height += retweetHeight
            }
        }
        
        height += pictureSize.height + margin + toolbarHeight
        
        rowHeight = height
        //原创微博高度
        //顶部部视图高度(12) + 间距(12) + 头像高度(34) + 间距(12) + 原创正文高度(计算) 
        //+ 配图视图高度(计算) + 间距(12) + 底部工具栏高度(35)
        //被转发微博高度
         //顶部部视图高度(12) + 间距(12) + 头像高度(34) + 间距(12) + 原创正文高度(计算)
        // + 间距(12) + 间距(12) + 被转发文本高度(计算)
        // + 配图视图高度(计算) + 间距(12) + 底部工具栏高度(35)
    }
}
